<template>
    <view class="section">
      <view v-if="loading" class="loading-form">
        <loading-modal />
      </view>
      <view v-else>
        <view class="section-title">估杆结果</view>
        <view class="section-content">
          <scroll-view
            scroll-y
            :scroll-into-view="scrollTo"
            class="section-content-scroll"
          >
            <view>
              <ua-markdown :source="markdown" />
              <!-- 添加锚点 view -->
              <view :id="'bottom-anchor'" style="height: 1px;" />
            </view>
          </scroll-view>
            <!-- <Markdown :source="markdown" /> -->
            <!-- <view v-for="(line, index) in output" :key="index">
                <text>{{ line }}</text>
            </view> -->
        </view>
      </view>
    </view>
  </template>
  
  <script setup>
  import { ref, nextTick } from 'vue'
  import { onLoad, onUnload } from '@dcloudio/uni-app'
  import { request } from '../utils/request'
  
  const loading = ref(true)
  const markdown = ref('')
  const querId = ref('')
  const scrollTo = ref('')
  const isError = ref(false)
  let socket = null
  
  const getData = (id) => {
    socket = uni.connectSocket({
      url: `ws://43.138.5.252:8878/ws`,
      header: {
        'Content-Type': 'application/json'
      },
      success: (res) => {
        console.log('WebSocket连接成功', res)
      }
    })
    socket.onOpen((res) => {
      console.log('WebSocket连接已打开', res, querId.value)
      socket.send({
        data: `auth:${id}`,
        success() {
          console.log('✅ 已发送认证信息')
          request({
            url: `/user/assess/generate/${querId.value}`,
            method: 'POST',
            header: {
              'Content-Type': 'application/x-www-form-urlencoded'
            },
            data: {
              id: querId.value
            }
          })
        },
        fail(err) {
          console.error('❌ 发送失败:', err)
        }
      })
    })
    // 接收服务器消息
    socket.onMessage((res) => {
      console.log('📩 收到消息:', res.data)
      loading.value = false;
       const line = res.data
      if(line === '_END_') {
        if (!isError.value) {
          markdown.value += '\n\n<div class="ai-note">—— 此估值价格由AI大模型生成，不代表本平台观点，请仔细甄别。 ——</div>'
        }
      } else if(line === '网络异常') {
        isError.value = true
        markdown.value = '网络异常，请重新估杆。'
      } else {
        if (!isError.value) {
          markdown.value += line
        }
      }
      nextTick(() => {
        setTimeout(() => scrollTo.value = 'bottom-anchor', 50)
      })
    })
    // 错误处理
    socket.onError((err) => {
      console.error('❌ WebSocket 错误:', err)
    })

    // 连接关闭时
    socket.onClose(() => {
      console.log('🔌 WebSocket 已关闭')
    })
    
  }
  
  onLoad((options) => {
    const id = decodeURIComponent(options.id)
    querId.value = id
    const userInfo = uni.getStorageSync('userInfo')
    getData(userInfo.id)
  })

  onUnload(() => {
    if (socket) {
      socket.close()
    }
  })

</script>
<style scoped>
.section {
    padding: 20rpx;
}
.section-title {
    font-size: 40rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
    text-align: center;
    color: #666;
}
.section-content{
    font-size: 28rpx;
    color: #888888;
    padding: 20rpx;
}
.loading-form{
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center
}
.section-content-scroll {
  height: 100vh;
  overflow: auto;
}
::v-deep .ai-note {
  margin-top: 60rpx;
  font-size: 20rpx;  /* 小字体 */
  color: #0e0e0e;       /* 灰色 */
  text-align: center;
}
</style>